package com.jhh.pay.center.service.impl;

import com.jhh.pay.center.model.OrderType;
import com.jhh.pay.center.service.FlowIdBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.text.SimpleDateFormat;
import java.util.Date;


@Service
@Slf4j
public class RedisFlowIdBuilder implements FlowIdBuilder {

    private static final String SEQ_KEY = "jhh:pay:seq_ids";

    @Autowired
    private JedisCluster jedisCluster;

    @Override
    public String newId(OrderType type) {
        SimpleDateFormat dateFmt = new SimpleDateFormat("yyyyMMdd");
        String date = dateFmt.format(new Date());
        long i = 0;
        try {
            i = jedisCluster.hincrBy(SEQ_KEY, date, 1L);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        if(i <= 0) {
            //6位
            i = (long)(Math.random() * 1000000);
        }
        String prefix = "P";
        if (type == OrderType.DEDUCT) {
            prefix = "D";
        }
        return String.format("%s%s%06d", prefix, date, i);
    }
}
